//
//  DSNetworkTool.m
//  DSJY
//
//  Created by XCY
//  Copyright (c) 2016年 HQ. All rights reserved.
//

#import "DSNetworkTool.h"
#import "MTConst.h"
#import "DSAccount.h"
#import "SVProgressHUD.h"
#import "DSMyLearnInfo.h"
#import "YQResponse.h"
#import "DSOrder.h"
//#import "AliyunOSSTool.h"
#import "NSDictionary+Extension.h"

@implementation DSNetworkTool

#pragma mark - 接口实现
+ (AFHTTPSessionManager *)session
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 90;
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
    [session.requestSerializer setValue:[MTUserDefaults objectForKey:sessionid] forHTTPHeaderField:@"sessionid"];
    return session;
}

+ (void)params:(NSDictionary *)params url:(NSString *)url
{
    //拼接
    NSString *urlAndParamsString = [params urlDictToStringWithUrlStr:url];
    MTLog(@"网址 \n\n %@", urlAndParamsString);
}

+ (void)GET:(NSString *)url dismiss:(BOOL)dismiss params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *session = [self session];
    [self params:params url:url];
    [session GET:url parameters:params progress:^(NSProgress *downloadProgress) {
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success) {
            [self dismissProgressHUDWithResponseObject:responseObject dismiss:dismiss];
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (failure) {
            [self dismissHUDWithCompletion:^{
                failure(error);
            }];
        }
    }];
}

+ (void)POST:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *session = [self session];
    [self params:params url:url];
    [session POST:url parameters:params progress:^(NSProgress *uploadProgress) {
        
    } success:^(NSURLSessionDataTask * task, id responseObject) {
        if (success) {
            [self dismissProgressHUDWithResponseObject:responseObject dismiss:YES];
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * task, NSError *error) {
        if (failure) {
            [self dismissHUDWithCompletion:^{
                failure(error);
            }];
        }
    }];
}

+ (void)POSTJson:(NSString *)url params:(id)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *session = [self session];
    [self params:params url:url];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    [session POST:url parameters:params progress:^(NSProgress *uploadProgress) {
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success) {
            [self dismissProgressHUDWithResponseObject:responseObject dismiss:YES];
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (failure) {
            [self dismissHUDWithCompletion:^{
                failure(error);
            }];
        }
    }];
}

+ (void)POST:(NSString *)url params:(id)params constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>))constructingBodyWithBlock progress:(void (^)(NSProgress *))progress success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *session = [self session];
    [self params:params url:url];
    [session POST:url parameters:params
        constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            if (constructingBodyWithBlock) {
                constructingBodyWithBlock(formData);
            }
        }progress:^(NSProgress *uploadProgress) {
            if (progress) {
                progress(uploadProgress);
            }
        } success:^(NSURLSessionDataTask *task, id responseObject) {
            if (success) {
                [self dismissProgressHUDWithResponseObject:responseObject dismiss:YES];
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            if (failure) {
                [self dismissHUDWithCompletion:^{
                    failure(error);
                }];
            }
        }
    ];
}

//根据responseObject的error_code判断是否需要dimissHUD
+ (void)dismissProgressHUDWithResponseObject:(NSDictionary *)responseObject dismiss:(BOOL)dismiss
{
    bool isContain = [[responseObject allKeys] containsObject:@"error_code"];
    if (isContain) {
        NSInteger code = [responseObject[@"error_code"] integerValue];
        if (code == YQResponseCodeError) {
            [SVProgressHUD showErrorWithStatus:responseObject[@"msg"]];
        }else{
            if (dismiss) {
                [self dismissHUDWithCompletion:nil];
            }
        }
    }
}

+ (void)dismissHUDWithCompletion:(void (^)())completion
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismissWithCompletion:completion];
        });
    });
}

#pragma mark - 各个模块的接口
+ (void)visitorsLoginWithSuccess:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"studentAction!appVisitorslogin.do"];
    //请求
    [self POST:urlString params:nil success:success failure:failure];
}

+ (void)loginWithParams:(DSAccount *)account success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"studentAction!applogin.do"];
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"loginEmail"] = account.loginid;
    params[@"loginPassword"] = account.loginPassword;
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

+ (void)regisgerWithParams:(DSAccount *)account success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"studentAction!appregist.do"];
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"name"] = account.loginid;
    params[@"password"] = account.loginPassword;
    params[@"mobile"] = account.mobile;
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

+ (void)learnInfoListWithParams:(DSAccount *)account pagenum:(NSInteger)pagenum pagecount:(NSInteger)pagecount success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"learninginfoAction!applearnInfoList.do"];
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"studentid"] = account.stuId;
//    params[@"pagenum"] = @(pagenum);
//    params[@"pagecount"] = @(pagecount);
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

+ (void)toDayHeroesListWithParams:(DSAccount *)account pagenum:(NSInteger)pagenum pagecount:(NSInteger)pagecount success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"learninginfoAction!apptodayheroeslist.do"];
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"studentid"] = account.stuId;
//    params[@"pagenum"] = @(pagenum);
//    params[@"pagecount"] = @(pagecount);
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

+ (void)monthHeroesListWithParams:(DSAccount *)account pagenum:(NSInteger)pagenum pagecount:(NSInteger)pagecount success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"learninginfoAction!appmonthheroeslist.do"];
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"studentid"] = account.stuId;
//    params[@"pagenum"] = @(pagenum);
//    params[@"pagecount"] = @(pagecount);
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

+ (void)indexWithParams:(DSAccount *)account pagenum:(NSInteger)pagenum pagecount:(NSInteger)pagecount success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = nil;
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (account) {
        //首页已登陆加载课程接口
        urlString = [DSDomain stringByAppendingString:@"indexAction!apploginedindex.do"];
        params[@"studentid"] = account.stuId;
    }else{
        //首页未登陆加载课程接口
        urlString = [DSDomain stringByAppendingString:@"indexAction!appindex.do"];
    }
    params[@"pagenum"] = @(pagenum);
    params[@"pagecount"] = @(pagecount);
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

+ (void)learnListWithParams:(DSAccount *)account bookid:(NSString *)bookid pagenum:(NSInteger)pagenum pagecount:(NSInteger)pagecount success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"unitAction!appstartlearnlist.do"];;
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"studentid"] = account.stuId;
    params[@"bookid"] = bookid;
    params[@"pagenum"] = @(pagenum);
    params[@"pagecount"] = @(pagecount);
    
    //请求
    [self POST:urlString params:params success:success failure:failure];
    
}

+ (void)downFileWithUrlString:(NSString *)urlString unitId:(NSString *)unitId success:(void (^)(NSString *urlString))success failure:(void (^)(NSError *error))failure
{
    [self downFileWithUrlString:urlString unitId:unitId index:@"" success:success failure:failure];
}

+ (void)downFileWithUrlString:(NSString *)urlString unitId:(NSString *)unitId index:(NSString *)index success:(void (^)(NSString *urlString))success failure:(void (^)(NSError *error))failure
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSString *fileName = [NSString stringWithFormat:@"%@%@%@", index, unitId, [response suggestedFilename]];
        NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
        
        //先删除之前的
        NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        [[NSFileManager defaultManager] removeItemAtPath:[path stringByAppendingPathComponent:fileName] error:nil];
        return url;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error != nil) {
            failure(error);
        }else{
            NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
            NSString *fileName = [NSString stringWithFormat:@"%@%@%@", index, unitId, [response suggestedFilename]];
            success([path stringByAppendingPathComponent:fileName]);
        }
    }];
    [downloadTask resume];
}

//+ (void)ossDownFileWithPath:(NSString *)path unitId:(NSString *)unitId success:(void (^)(NSString *urlString))success failure:(void (^)(NSError *error))failure
//{
//    NSString *originalName = [path lastPathComponent];
//    NSString *downPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:originalName];
//    
//    if ([path hasPrefix:@"/"]) { //是否以"/"开头
//        path = [path substringFromIndex:1];
//    }
//    //去下载最新的
//    OSSTask *task = [[[AliyunOSSTool alloc] init] downloadObjectAsyncWithPath:downPath objectKey:path];
//    [task continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
//        if (!task.error) {
//            MTLog(@"download object success!");
//            //先删除之前的
//            NSString *fileName = [NSString stringWithFormat:@"%@%@", unitId, [path lastPathComponent]];
//            NSString *newPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:fileName];
//            NSFileManager *manager = [NSFileManager defaultManager];
//            [manager removeItemAtPath:newPath error:nil];
//            
//            //改名
//            [manager moveItemAtPath:downPath toPath:newPath error:nil];
//            dispatch_sync(dispatch_get_main_queue(), ^{
//                success(newPath);
//            });
//        } else {
//            MTLog(@"download object failed, error: %@" ,task.error);
//            dispatch_sync(dispatch_get_main_queue(), ^{
//                failure(task.error);
//            });
//        }
//        return nil;
//    }];
//}

+ (void)learnCourseWithParams:(DSAccount *)account unitid:(NSString *)unitid userExist:(BOOL)userExist success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    
    //url
    NSString *urlString = nil;
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (unitid) {
        //点击单元进行学习接口
        urlString = [DSDomain stringByAppendingString:@"unitAction!applearnCourse.do"];
        params[@"unitid"] = unitid;
    }else{
        //点击导航菜单进入最近一次单元练习
        urlString = [DSDomain stringByAppendingString:@"unitAction!applearnLastCourse.do"];
        params[@"userExist"] = @(userExist);
    }
    params[@"studentid"] = account.stuId;
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

+ (void)insertMyLearninginfoWithParams:(DSMyLearnInfo *)myLearnInfo success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"learninginfoAction!appinsertLearninginfo.do"];;
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"studentid"] = myLearnInfo.studentid;
    params[@"unitid"] = myLearnInfo.unitid;
    params[@"stime"] = @(myLearnInfo.stime);
    params[@"score"] = @(myLearnInfo.score);
    params[@"iflastunit"] = @(myLearnInfo.iflastunit);
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

+ (void)orderPayWithParams:(DSAccount *)account year:(NSString *)year channel:(NSString *)channel success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"appAlipay_orderPay.do"];;
    
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"studentid"] = account.stuId;
    params[@"year"] = year;
    params[@"channel"] = channel;
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

+ (void)studentOrderListWithParams:(DSAccount *)account channel:(NSString *)channel success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"stuandbookAction!appStudentOrderList.do"];
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"studentid"] = account.stuId;
    params[@"channel"] = channel;
    //请求
    [self GET:urlString dismiss:YES params:params success:success failure:failure];
}

+ (void)iapWithParams:(DSAccount *)account year:(NSString *)year channel:(NSString *)channel receipt:(NSString *)receipt chooseEnv:(BOOL)chooseEnv success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"iap_setIapCertificate.do"];
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"studentid"] = account.stuId;
    params[@"receipt"] = receipt;
    params[@"chooseEnv"] = @(chooseEnv);
    params[@"year"] = year;
    params[@"channel"] = channel;
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

+ (void)getIapProductsWithSuccess:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"iap_getIapProducts.do"];
    //请求
    [self GET:urlString dismiss:NO params:nil success:success failure:failure];
}

+ (void)updateSharescoreWithParams:(DSAccount *)account sharescore:(NSString *)sharescore success:(void (^)(NSDictionary *responseObject))success failure:(void (^)(NSError *error))failure
{
    //url
    NSString *urlString = [DSDomain stringByAppendingString:@"studentAction!appUpdateSharescore.do"];;
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"studentid"] = account.stuId;
    params[@"sharescore"] = sharescore;
    //请求
    [self POST:urlString params:params success:success failure:failure];
}

@end
